package top.yangwulang.demo3.controller;

import io.swagger.v3.oas.annotations.Operation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import top.yangwulang.demo3.entity.*;
import top.yangwulang.demo3.repository.UserRepository;
import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.dev33.satoken.stp.StpUtil;
import cn.dev33.satoken.util.SaResult;

import java.util.ArrayList;
import java.util.Collection;
import java.util.*;

@RestController
@RequestMapping("/test")
public class TestController {

    @Autowired
    private UserRepository repository;

    @SaCheckPermission(value = "sys:dictType:view")
    @GetMapping("/t")
    @Operation(summary = "测试")
    public List<String> getMapping() {
        Optional<User> user = repository.findById("1614867934644609024",
                Fetchers.USER_FETCHER.loginCode()
                        .roles(
                                RoleFetcher.$.menus(
                                        MenuFetcher.$.allScalarFields()
                                )
                        )
        );
        return user.map(it -> {
                    return it.roles()
                            .stream()
                            .map(Role::menus)
                            .flatMap(Collection::stream)
                            .map(Menu::permission)
                            .filter(s -> s != null && !s.isEmpty())
                            .toList();
                }
        ).orElseGet(ArrayList::new);
    }


    @GetMapping("/login")
    @Operation(summary = "登录")
    public SaResult login(String loginCode, String password) {
        User user = repository.findByLoginAndPassword(
                loginCode, UserRepository.encryptPassword(password)
        );
        StpUtil.login(user.userCode(), "WEB");
        return SaResult.data(StpUtil.getTokenInfo());
    }
}
